#ifndef _UDP_SERVER_HPP__
#define _UDP_SERVER_HPP__


#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <cerrno>
#include <strings.h>
#include <functional>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "InetAddr.hpp"
#include "Log.hpp"
#include "Common.hpp"
#include "ThreadPool.hpp"

using namespace LogModule;
using namespace ThreadPoolModule;

const static int gsockfd = -1;
const static uint16_t gdefaultport = 8080; 

using adduser_t = std::function<void (InetAddr &id)>;
using remove_t = std::function<void(InetAddr &id)>;

using route_t = std::function<void(int sockfd, const std::string &message)>;
using task_t =  std::function<void()>;


class nocopy
{
public:
    nocopy(){}
    nocopy(const nocopy &) = delete;
    const nocopy& operator = (const nocopy &) = delete;
    ~nocopy(){};
};

class UdpServer : public nocopy
{
public:
    UdpServer(adduser_t adduser, uint16_t port = gdefaultport)
    : _sockfd(gsockfd),
      _addr(port),
      _isrunning(false),
      _adduser(adduser)
    {
    }

    // 都是套路
    void InitServer()
    {
        // 1. 创建套接字 socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0); // IP Port 网络 本地
        if(_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is : " << _sockfd; // 测试

        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());

        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success"; // 测试
    }

    void RegisterService(adduser_t adduser, route_t route, remove_t removeuser)
    {
        _adduser = adduser;
        _route = route;
        _removeuser = removeuser;
    }

    void Start()
    {   
        _isrunning = true; // 启动服务器
        
        while(true) // 服务器不能停
        {
            char inbuffer[1024]; // string
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer); // 必须设定

            ssize_t n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, CONV(&peer), &len) ; // -1 预留一个空位置给 \0，这里 0 表示采用阻塞的方式进行等待
            if(n > 0)
            {   
                // 1. 消息内容 && 谁发的
                InetAddr cli(peer);
                inbuffer[n] = 0;
        
                // std::string message = inbuffer;
                // 2. 新增用户
                //_adduser(cli);

                std::string message;
                if(strcmp(inbuffer, "QUIT") == 0) {
                    // 移除观察者
                    _removeuser(cli);
                    message = cli.Addr() + " #" + "我走了，你们聊! ";
                }
                else{
                    // 2. 新增用户
                    _adduser(cli);
                    message = cli.Addr() + "# " + inbuffer;
                }

                // 3. 构建转发任务，推送给线程池，让线程池进行转发
                task_t task = std::bind(UdpServer::_route, _sockfd, message); // route 是回调方法，不是成员方法 不用 this
                ThreadPool<task_t>::getInstance()->Equeue(task);

                // std::string clientinfo = cli.GetIp() + ":" + std::to_string(cli.GetPort()) + " # " + inbuffer;

                // // LOG(LogLevel::DEBUG) << "client say@" << inbuffer; 
                // LOG(LogLevel::DEBUG) << clientinfo;

                // std::string echo_string = "echo# ";
                // echo_string += inbuffer;

                // ::sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, CONV(&peer), sizeof(peer));
            }
        }
        _isrunning = false;
    }

    ~UdpServer()
    {
        if(_sockfd > gsockfd)
            ::close(_sockfd);
    }

private:
    int _sockfd; 
    InetAddr _addr;
    bool _isrunning; // 服务器运行状态

    adduser_t _adduser;     // 新增用户
    remove_t _removeuser;   // 移除用户
    route_t _route;         // 数据转发
};


#endif